﻿using System.Text;

namespace Pvf.Core.Contents
{
    /// <summary>
    /// 
    /// </summary>
    public static class PvfIndexExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="indexRef"></param>
        /// <typeparam name="TObj"></typeparam>
        /// <returns></returns>
        public static TObj GetObjectContent<TObj>(this PvfIndexRef indexRef)
        {
            if (indexRef == null)
            {
                return default;
            }
            var tmpObj = GetObjectContent<TObj>(indexRef.GetRef(), indexRef.Module, indexRef.Index);
            if (tmpObj is PvfObjectBase pvfObject)
            {
                pvfObject.ObjectId = indexRef.Index;
            }
            return tmpObj;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TObj"></typeparam>
        /// <param name="index"></param>
        /// <param name="module"></param>
        /// <param name="objId"></param>
        /// <returns></returns>
        public static TObj GetObjectContent<TObj>(this PvfIndex index, IPvfModule module, int objId)
        {
            var obj = index?.GetContent<PvfObjectContent<TObj>>(Encoding.GetEncoding("UTF-8"), module);
            if (obj is PvfObjectBase pvfObject)
            {
                pvfObject.ObjectId = objId;
            }
            return obj != null ? obj.Data : default;
        }
    }
}
